package com.gec.yhzh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gec.yhzh.Exception.UserAlreadyExistsException;
import com.gec.yhzh.entity.User;
import com.gec.yhzh.entity.UserDTO;
import com.gec.yhzh.mapper.UserMapper;
import com.gec.yhzh.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 患者用户 服务实现类
 * </p>
 *
 * @author jerry
 * @since 2025-03-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private final UserMapper userMapper;;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public boolean register(UserDTO userDTO) throws UserAlreadyExistsException {

        // 检查用户名是否已存在
        if (this.findByName(userDTO.getName())){
            throw new UserAlreadyExistsException("用户名已存在");
        }
        // 将 DTO 转换为实体
        User user = new User();
        user.setName(userDTO.getName());
        user.setSex(userDTO.getSex());
        user.setAge(userDTO.getAge());
        user.setPassword(userDTO.getPassword());
        user.setImage(userDTO.getImage());
        user.setCodeid(userDTO.getCodeid());
        user.setPhone(userDTO.getPhone());
        user.setAddress(userDTO.getAddress());

        // 保存用户到数据库
        this.save(user);

        return true;
    }

    @Override
    public boolean findByName(String name) {
        User one = this.getOne(new LambdaQueryWrapper<User>().eq(User::getName, name));
        return one != null?true:false;
    }


    @Override
    public User getUserById(Integer id) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getId, id);
        return super.getOne(lqw);
    }

    @Override
    public User Login(String phone, String password) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,phone);
        queryWrapper.eq(User::getPassword, password);
        User one = this.getOne(queryWrapper);
        return one;
    }

}
